from fastapi import FastAPI
from fastapi.params import Query
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from db import game_data_collection
from bson import json_util
from model.common import ErrorResponseModel, ResponseModel
from model.data import TotalDataModel
from starlette.requests import Request

app = FastAPI()

type_strs = ['fps', 'memory_usage', 'temperature', 'vmSize', 'battery']

# 跨域设置
app.add_middleware(
    CORSMiddleware,
    allow_origins= ["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 测试界面
@app.get('/')
async def get_main(request: Request):
    return "Hello World"

# 案例列表接口
@app.get('/case_list')
async def get_case():
    try:
        result_list = []
        async for i in game_data_collection.find({}, {'caseID': '$caseID', 'deviceName': '$deviceName','sceneName': '$sceneName','gatherTime': '$gatherTime','totalPower': '$totalPower', '_id': 0}):
            result_list.append(i)
        return ResponseModel(result_list, 'succeed')
    except Exception as e:
        return ErrorResponseModel("An error occurred.", 404, f"{e}")

# 单个案例的数据
@app.get('/case_data/{case_id}')
async def get_case(case_id : str):
    try:
        data = await game_data_collection.find_one({'caseID' : case_id}, {'fps':'$fps','memory_usage':'$memory usage','temperature':'$temperature','vmSize':'$vmSize','battery':'$battery','_id': 0})
        return ResponseModel(data, 'succeed')
    except Exception as e:
        return ErrorResponseModel("An error occurred.", 404, f"{e}")


# 单个案例的数据
@app.get('/case_total_data/{case_id}')
async def get_case(case_id : str):
    try:
        data = {}
        result = await game_data_collection.find_one({'caseID' : case_id}, {'fps':'$fps','memory_usage':'$memory usage','temperature':'$temperature','vmSize':'$vmSize','battery':'$battery','_id': 0})
        for i in range (len(type_strs)):
            data[f'{type_strs[i]}_total_data'] = TotalDataModel(result[type_strs[i]])
        return ResponseModel(data, 'succeed')
    except Exception as e:
        return ErrorResponseModel("An error occurred.", 404, f"{e}")
